package com.kfm.servlet;

import com.kfm.dao.UploadFileDao;
import com.kfm.utils.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;

@WebServlet("/uploadFiles")
// 支持文件上传
@MultipartConfig
public class UploadServlet extends HttpServlet {

    private UploadFileDao dao = new UploadFileDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("upload.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理POST请求的逻辑
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        Collection<Part> parts = req.getParts();
        // 构建前端响应字符串
        StringBuilder message = new StringBuilder();
        StringBuilder aLink = new StringBuilder();
        // 获取IP地址
        String remoteAddr = req.getRemoteAddr();
        remoteAddr = "0:0:0:0:0:0:0:1".equals(remoteAddr) ? "127.0.0.1" : remoteAddr;
        for (Part part : parts) {
            // 1. 保存到服务器某个地址中
            // 2. 保存到数据库 id IP地址 文件名称 文件大小 文件类型 上传时间 下载地址
            // 文件上传时候的名称
            String fileName = part.getSubmittedFileName();
            String name = fileName.substring(0, fileName.lastIndexOf("."));
            long size = part.getSize();
            String type = part.getContentType();
            if (Constant.ALLOW_UPLOAD_TYPE.contains(type)) {
                String upload = Constant.UPLOAD_PATH + File.separator + fileName;
                File file = new File(upload);
                // 判断上传的父级目录是否存在
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                try {
                    // 将文件写到指定文件中
                    part.write(upload);
                    System.out.println(fileName + "上传成功");
                    // 构建响应信息
                    message.append("<p style='color:green;'>").append(fileName).append("上传成功！</p>");
                    // 构建下载链接 直接用名字 下载的时候中文无法下载
                    String link = "http://" + remoteAddr + ":80/download?file=" + fileName;
                    aLink.append("<a href='").append(link).append("'>下载").append(name).append("</a>");
                    // 将上传的信息插入数据库
                    int i = dao.add(remoteAddr, name, String.valueOf(size), type, link);
                    if (i > 0) {
                        System.out.println("保存数据库成功");
                    } else {
                        System.out.println("保存数据库失败");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    message.append("<p style='color:red;'>").append(fileName).append("上传失败！</p>");
                }
            } else {
                message.append("<p style='color:red;'>").append(fileName).append("上传失败，文件类型不支持！</p>");
            }
        }

        String htmlResponse = "<html><body>";
        htmlResponse += message;
        htmlResponse += aLink;
        htmlResponse += "</body></html>";

        // 将响应信息反馈给前端
        resp.getWriter().write(htmlResponse);
    }
}
